﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Api.Common
{
    public static class StringExtend
    {
        /// <summary>
        /// 返回object的指定长度
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string SubStr(this object obj, int length = 0)
        {
            if (obj == null || string.IsNullOrEmpty(obj.ToString())) return string.Empty;
            var str = obj.ToString();
            if (str.Length > length && length != 0)
            {
                return str.Substring(0, length);
            }
            return str;
        }

        /// <summary>
        /// 移除字符串中非大小寫和字母的其他字符，主要是為了作為文件名來保存文件
        /// </summary>
        /// <param name="data">數據</param>
        /// <param name="ext">擴展名</param>
        /// <returns></returns>

        public static string GetFileName(this string data, string ext)
        {
            if (string.IsNullOrEmpty(data)) return string.Empty;
            string value = data;

            Regex reg = new Regex(@"([a-zA-Z0-9])");
            StringBuilder sb = new StringBuilder();
            foreach (var item in value.ToCharArray())
            {
                string s = item.ToString();
                var match = reg.Match(s);
                if (match.Success)
                {
                    sb.Append(s);
                }
            }
            sb.AppendFormat("_{0}", DateTime.Now.ToString("yyyymmddHHmmssff"));
            sb.Append(ext);
            return sb.ToString();

        }
    }
}
